package preorderlayer

import (
    "time"
    "errors"
	"strings"
	"strconv"
	"encoding/json"
	"dhfshop/models/consts"
	"github.com/astaxie/beego"
	"dhfshop/models/preorder"
)

func TemplateToHub(partnerId, storeId, templateId int64) (templateHub *preorder.TemplateHub, err error){
	template, e := preorder.GetTemplateById(templateId)
	if e != nil {
		err = e
		return nil, err
	}
	templateTmp := new(preorder.TemplateTmp)
	if err = json.Unmarshal([]byte(template.PeriodsJson), templateTmp); err != nil {
		return nil, err
	}
	templateHub = &preorder.TemplateHub{
		PartnerId:     partnerId,
		StoreId:       storeId,
		TemplateId:    templateId,
		TypeId:        template.TypeId,
		ExcludeByWeek: template.ExcludeByWeek,
		ExcludeByDate: template.ExcludeByDate,
		PeriodMaps:  make(map[string]*preorder.PeriodStl),
	}
	for _, value := range templateTmp.Periods {
		templateHub.PeriodMaps[strconv.Itoa(value.PeriodNo)] = value	
	}
	return
}

// 实例化一天的数据
func ModelToDay(resItemId int64, templateHub *preorder.TemplateHub, delayDay int) (period *preorder.Periods, err error){
	weekMap := map[string]string{
		"Monday":    "1",
		"Tuesday":   "2",
		"Wednesday": "3",
		"Thursday":  "4",
		"Friday":    "5",
		"Saturday":  "6",
		"Sunday":    "7",
	}
	srcDate := time.Now().UTC().Add(time.Duration(delayDay)*24*time.Hour)
	srcDateDay := srcDate.Format("20060102")
	weekDay := srcDate.Weekday().String()
	if periodId, _:= preorder.GetPeriodsIdByDate(srcDate, resItemId, 0); periodId > -1 {
	    if ok := preorder.ExistPreOrder(resItemId, periodId, 0); ok {
	        err = errors.New("pre order is exist")
			beego.Debug(err.Error())
			return
	    }
		preorder.DeletePeriodsById(periodId)
	}
	weekNo := "1" 
	if tmp, ok := weekMap[weekDay]; ok {
		weekNo = tmp
	}
	//查找需要避开的日期
	if ok := strings.Contains(templateHub.ExcludeByWeek, weekNo); ok {   
		beego.Debug("week no need exclude:", weekNo)
		err = errors.New("week no need exclude")
		return    
	}
	if ok := strings.Contains(templateHub.ExcludeByDate, srcDateDay); ok {   
		beego.Debug("date day need exclude:", srcDateDay)
		err = errors.New("date day need exclude")
		return    
	}
	if templateHub.TypeId == 2 {  //天的模板需要处理
        weekNo = "1"
    }
	if periodStl, ok := templateHub.PeriodMaps[weekNo]; ok {
		period = new(preorder.Periods)
		period.PartnerId = templateHub.PartnerId
		period.ResItem, _ = preorder.GetResItemById(resItemId)
		period.ResItemId = resItemId
		period.Name = periodStl.Name
		period.SourceAt = srcDate
		period.SourceAtStr = period.SourceAt.Format(consts.DATE_FORMAT)
		for _, slotSTL := range periodStl.Timeslots {
			timeslot := &preorder.Timeslots{
				PartnerId: templateHub.PartnerId,
				TimeslotNo: slotSTL.TimeslotNo,
				Periods: period,
				Start: slotSTL.Start,
				End: slotSTL.End,
				CurCount: 0,
				MaxCount: slotSTL.MaxCount,
			}
			period.Timeslots = append(period.Timeslots, timeslot)
		}
	}else{
		err = errors.New("there is not the weekday:" + strconv.FormatInt(resItemId,10))
	}
	return
}

// 实例化多天的数据
func ModelToMultiDay(resItemId int64,templateHub *preorder.TemplateHub,reserveDays int)(periods []*preorder.Periods,err error){
	//删除此预约对象所有未发布的实例
	preorder.DeletePeriodsByPublish(templateHub.PartnerId,resItemId)
	//
	periods = []*preorder.Periods{}
	totalCountDays := 1
    beego.Debug("reserveDays:", reserveDays)
	curTime := time.Now().UTC()
	start := curTime.Add(time.Duration(-10)*24*time.Hour).Format("20060102")
	end := curTime.Add(time.Duration(-1)*24*time.Hour).Format("20060102")
	preorder.DeletePeriodsByMultiCond(templateHub.PartnerId,resItemId,0,start,end)
	//
	for totalCountDays <= reserveDays {
		if period, err := ModelToDay(resItemId,templateHub, totalCountDays); err == nil {
		    periods = append(periods, period)
		}
		totalCountDays++
    }
	b, _ := json.Marshal(periods)
	beego.Debug("ModelToMultiDay:", string(b))
	return
}
